<template>
  <el-dialog
    :title="title"
    :visible.sync="openSheet"
    width="1100px"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    append-to-body
    :before-close="cancel"
  >
    <el-form ref="form" :model="form" :rules="formRules" label-width="160px">
      <el-form-item
        v-for="(item, index) in fixedItems"
        :key="index"
        :label="item.label"
      >
        <el-input
          v-model="form[item.label]"
          :placeholder="item.placeholder || '请输入'"
          :disabled="item.disabled"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-if="createFlag" type="primary" @click="submitForm">{{
        $t('create')
      }}</el-button>
      <el-button v-else type="primary" @click="submitForm">{{
        $t('update')
      }}</el-button>
      <el-button @click="cancel">{{ $t('cancel') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createProjectPlanCommonApi, updateProjectPlanCommonApi } from './projectplancommon.api';

export default {
  name: 'FixedItemForm',
  props: {
    // 父组件传来的参数，section
    section: {
      type: String,
      required: true,
      description: '' // 固定的section值（如"法律"）
    },
    // 父组件中传来的列表参数，用来生成表单的固定项
    fixedItems: {
      type: Array,
      required: true,
      description: '', // 固定item配置，格式：[{key: "item1", label: "标签1", placeholder: "提示"}]
      default: () => []
    },
    // 父组件中修改画面传来当前项目计划书ID对应的数据
    formData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗标题
    title: {
      type: String,
      default: '项目计划辅助信息' // 弹窗标题
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {}, // 存储输入值
      openSheet: false,
      createFlag: true,
      queryparms: {
        projectPlanFK: undefined,
        section: undefined,
        itemlist: []
      }
    }
  },
  computed: {
    formRules() {
      // 自动生成校验规则（根据item是否必填）
      const rules = {}
      this.fixedItems.forEach(item => {
        rules[item.label] = [{
          required: item.required !== false,
          message: `${item.label}不能为空`,
          trigger: 'blur'
        }]
      })
      return rules
    }
  },
  created() {
    // this.initFormData();
  },
  methods: {
    // 初始化，data对应的是maintain中的项目计划信息，customedata对应的是maintain中的项目计划客户信息
    async openSheetDialog(data, commondata) {
      this.openSheet = !this.openSheet;
      this.reset();
      if (commondata) {
        this.createFlag = false;
        this.projectPlanId = data.id;
        this.initFormData()
        this.form = { ...commondata };
      } else {
        this.createFlag = true;
        this.projectPlanId = data.id;
      }
    },
    initFormData() {
      // 初始化表单值：优先使用父组件传递的formData，无则留空
      this.fixedItems.forEach(item => {
        this.form[item.label] = this.formData[item.label] || '';
      });
    },
    cancel() {
      this.openSheet = !this.openSheet;
    },
    reset() {
      this.resetForm('form');
      this.resetJsonObject(this.form)
    },
    submitForm: function() {
      this.$refs['form'].validate(async(valid) => {
        if (valid) {
          var resp;
          const itemlist = this.fixedItems.map(item => ({
            item: item.label,
            value: this.form[item.label]
          }))
          this.queryparms.itemlist = itemlist
          this.queryparms.projectPlanFK = this.projectPlanId
          this.queryparms.section = this.section
          if (this.createFlag) {
            resp = await createProjectPlanCommonApi({ ...this.queryparms });
          } else {
            resp = await updateProjectPlanCommonApi({ ...this.queryparms });
          }
          if (resp.success) {
            this.$emit('refreshList');
            this.cancel();
            if (this.createFlag) {
              this.targaMessage(
                this.$t('createSuccessNoInfo')
              );
            } else {
              this.targaMessage(
                this.$t('updateSuccessNoInfo')
              );
            }
          } else {
            if (typeof resp.msg === 'object') {
              this.error = resp.msg;
            } else {
              this.targaMessageBox(this, resp.msg);
            }
          }
        }
      });
    }
  }
};
</script>

  <style scoped>
  /* 调整输入框的字数统计的样式，让其向下、向右移动，不会遮挡输入的文字 */
  ::v-deep .el-textarea .el-input__count {
    font-size: 10px;
    bottom: -6px;
    right: 2px;
  }
  </style>
